using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class forums_controls_administration_YCodeTransforms: Controls.DataManagerYCodeControl
{
    
    protected override void ItemChanged()
    {
        Refresh();
    }

    private DAL.YCodeTransform GetSelectedItem(object o)
    {
        long id;
        if (o != null && Int64.TryParse(o.ToString(), out id))
        {
            return DAL.YCodeTransforms.Item(id);
        }
        else
        {
            return null;
        }
    }

    public void Refresh()
    {
        gridItems.DataSource = DAL.YCodeTransforms.GetByYCode(CurrentYCode);
        gridItems.DataBind();
    }

    protected void Move(object sender, CommandEventArgs e)
    {
        DAL.YCodeTransform myItem = GetSelectedItem(e.CommandArgument);
        if (myItem != null)
        {
            switch (e.CommandName.ToLower())
            {
                case "up":
                    DAL.YCodeTransforms.Move(myItem, DAL.Direction.Up);
                    break;
                default:
                    DAL.YCodeTransforms.Move(myItem, DAL.Direction.Down);
                    break;
            }
        }
        Refresh();
    }

    private t GetControl<t>(Control parent, string controlName)
        where t : Control
    {
        return (t)parent.FindControl(controlName);
    }

    protected void SaveTransform(object sender, CommandEventArgs e)
    {
        Control parent = (sender as Control).Parent;
        TextBox txtPattern = GetControl<TextBox>(parent, "txtPattern");
        TextBox txtReplacement = GetControl<TextBox>(parent, "txtReplacement");
        DAL.YCodeTransform myTransform = GetSelectedItem(e.CommandArgument);

        if (txtPattern != null && txtReplacement != null && myTransform != null)
        {
            myTransform.Pattern = txtPattern.Text;
            myTransform.Replacement = txtReplacement.Text;
            DAL.YCodeTransforms.Save(myTransform);        
        }
    }

    protected void DeleteItem(object sender, CommandEventArgs e)
    {
        DAL.YCodeTransform myCode = GetSelectedItem(e.CommandArgument);
        if (myCode != null)
        {
            DAL.YCodeTransforms.Remove(myCode);
            Refresh();
        }
    }
}